package simplescenegraph.assets.models.obj;

import java.util.ArrayList;
import java.util.List;

import simplescenegraph.Material;
import simplescenegraph.Node;
import simplescenegraph.Renderer;
import simplescenegraph.math.Vector2f;
import simplescenegraph.math.Vector3f;

public class OBJGroup {
	
	private OBJModel model;
	
	@SuppressWarnings("unused")
	private String name;
	
	private String materialName;
	
	private List<OBJElement> elements = new ArrayList<OBJElement>();
	
	public OBJGroup(OBJModel model, String name) {
		if (model == null || name == null || name.isEmpty()) {
			throw new IllegalArgumentException();
		}
		
		this.name = name;
		this.model = model;
		this.model.addGroup(this);
		
		materialName = OBJModel.DEFAULT_MATERIAL_NAME;
	}

	public void setUseMaterial(String useMaterial) {
		if (useMaterial == null) {
			throw new IllegalArgumentException();
		}
		
		this.materialName = useMaterial;
	}

	public OBJModel getModel() {
		return model;
	}

	public void addElement(OBJFace element) {
		if (element == null) {
			throw new IllegalArgumentException();
		}
		
		elements.add(element);
	}
	
	public void prepare(boolean calculateVertexesNormals) {
		Material material = model.getMaterial(materialName);
		for (OBJElement element : elements) {
			element.prepare(calculateVertexesNormals);
			element.setMaterial(material);
			
			// TODO: Refactory
			if (model.getBoundingVolume() == null) {
				model.setBoundingVolume(element.getBoundingVolume().copy());
			} 
			else {
				model.getBoundingVolume().merge(element.getBoundingVolume());
			}
		}
	}
	
	public void draw(Renderer renderer) {
		for (OBJElement element : elements) {
			element.draw(renderer);
		}
	}
	
	public void updateLeafNode() {
		for (OBJElement element : elements) {
			element.setLeafNode(model.getLeafNode());
		}
	}

	public Vector3f getPositionByIndex(int index) {
		if (index < 0) {
			throw new IllegalArgumentException();
		}
		
		return model.getPositionByIndex(index);
	}

	public Vector3f getNormalByIndex(int index) {
		if (index < 0) {
			throw new IllegalArgumentException();
		}
		
		return model.getNormalByIndex(index);
	}

	public Vector2f getUVCoordinateByIndex(int index) {
		if (index < 0) {
			throw new IllegalArgumentException();
		}
		
		return model.getUVCoordinateByIndex(index);
	}

	public Node getLeafNode() {
		return model.getLeafNode();
	}

}